package com.meida.common.utils;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;

/**
 * 3DES加密工具类
 * https://www.cnblogs.com/innchina/p/5066396.html
 */
public class Des3Util {
    // 密钥 长度不得小于24
    private final static String secretKey = "flymemeidazhongguo@163.com";
    // 向量 可有可无 终端后台也要约定
    private final static String iv = "12345678";
    // 加解密统一使用的编码方式
    private final static String encoding = "utf-8";
    private static Cipher cipher;
    private static IvParameterSpec ips;
    private static Key desKey = null;

    static {
        try {
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("desede");
            desKey = keyFactory.generateSecret(spec);
            cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            ips = new IvParameterSpec(iv.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 3DES加密
     *
     * @param plainText 普通文本
     * @return
     * @throws Exception
     */
    public static String encode(String plainText) {
        try {
            cipher.init(Cipher.ENCRYPT_MODE, desKey, ips);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            return Base64Encoder.encode(encryptData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 3DES解密
     *
     * @param encryptText 加密文本
     * @return
     * @throws Exception
     */
    public static String decode(String encryptText) {
        try {
            cipher.init(Cipher.DECRYPT_MODE, desKey, ips);
            byte[] decryptData = cipher.doFinal(Base64Decoder.decode(encryptText));
            return new String(decryptData, encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String args[]) {
        String str = "18901336592";
        System.out.println("----加密前-----：" + str);
        String encodeStr = Des3Util.encode(str);
        System.out.println("----加密后-----：" + encodeStr);
        System.out.println("----解密后-----：" + Des3Util.decode(encodeStr));
    }
}